package com.hqyj.service.impl;

import com.hqyj.pojo.R;
import com.hqyj.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
    //注入邮件发送类
    @Autowired
    JavaMailSender javaMailSender;

    //读取发件人邮箱
    @Value("${spring.mail.username}")
    String email;
    @Override
    public R send(String toEmail, String title, String content) {
        log.info("-------邮件发送服务-------");
        //创建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        //设置收件人
        message.setTo(toEmail);
        //设置发件人
        message.setFrom(email);
        //设置邮件标题
        message.setSubject(title);
        //设置邮件正文
        message.setText(content);
        try{
            //发送邮件
            javaMailSender.send(message);
            log.info("邮件送成功");
            return R.ok("邮件送成功");
        }catch (Exception e){
            log.info("邮件送失败");
            e.printStackTrace();
        }
        return R.error();
    }
}
